﻿using System.Threading.Tasks;
using System.Linq;
using ECommon.Components;
using ECommon.IO;
using ENode.Infrastructure;
using Domain.Replies;
using Infrastructure;

namespace Denormalizers.Ef
{
    [Component]
    public class ReplyDenormalizer : AbstractDenormalizer,
        IMessageHandler<ReplyCreatedEvent>,
        IMessageHandler<ReplyBodyChangedEvent>
    {
        public Task<AsyncTaskResult> HandleAsync(ReplyCreatedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                db.Reply.Add(new Repository.EntityFramework.Forums.Reply
                { 
                    Id = evnt.AggregateRootId,
                    PostId = evnt.PostId,
                    ParentId = evnt.ParentId,
                    AuthorId = evnt.AuthorId,
                    Body = evnt.Body,
                    CreatedOn = evnt.Timestamp,
                    UpdatedOn = evnt.Timestamp,
                    Version = evnt.Version
                });
                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
        public Task<AsyncTaskResult> HandleAsync(ReplyBodyChangedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                var m = db.Reply.Where(x => x.Id == evnt.AggregateRootId && x.Version == evnt.Version - 1).SingleOrDefault();

                m.Body = evnt.Body;
                m.UpdatedOn = evnt.Timestamp;
                m.Version = evnt.Version;

                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
}
